package com.rmfyzxfw.caseprocess.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Map;

@Configuration
@ConditionalOnClass(DruidDataSource.class)
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
@EnableConfigurationProperties({DruidStatProperties.class, DataSourceProperties.class})
public class DataSourceConfig {

    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Bean("defaultDataSource")
//    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource defaultDataSource() {
        return DataSourceBuilder.create()
                .password(dataSourceProperties.getPassword())
                .driverClassName(dataSourceProperties.getDriverClassName())
                .username(dataSourceProperties.getUsername())
                .url(dataSourceProperties.getUrl())
                .type(dataSourceProperties.getType())
                .build();
    }

    @Bean
    @Primary
    public DataSourceRouting routingDataSource(@Qualifier("defaultDataSource") DataSource defaultDataSource) {
        DataSourceRouting router = new DataSourceRouting();
        Map<Object, Object> dataSources = Maps.newHashMap();
        dataSources.put("defaultDataSource", defaultDataSource);
        router.setTargetDataSources(dataSources);
        router.setDefaultTargetDataSource(defaultDataSource);
        return router;
    }

    @Bean
    public DataSourceTransactionManager transactionManager(DataSourceRouting dataSourceRouting) {
        return new DataSourceTransactionManager(dataSourceRouting);
    }
}
